package com.lktx.auto.controller;

import cn.hserver.plugin.web.annotation.WebSocket;
import cn.hserver.plugin.web.handlers.Ws;
import cn.hserver.plugin.web.interfaces.WebSocketHandler;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lktx.auto.bean.ChatMessage;
import com.lktx.auto.browser.BrowserSpider;
import com.lktx.auto.chat.ChatHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@WebSocket("/chat")
public class ChatWebSocket implements WebSocketHandler {

    private static final Map<String, ChatMessage> chatMessageMap = new ConcurrentHashMap<>();

    @Override
    public void onConnect(Ws ws) {

    }

    @Override
    public void onMessage(Ws ws) {
        String chatId = ws.query("chatId");
        if (chatId == null) {
            return;
        }
        String message = ws.getMessage();
        JSONObject entries = JSONUtil.parseObj(message);
        String type = entries.getStr("type");
        String msg = entries.getStr("msg");
        //指令解析
        if (msg.startsWith("招聘:")){
            String resume = BrowserSpider.getResume(msg.substring(3), 1);
            System.out.println(resume);
            msg=resume+"\n帮我把这个json数据转成表格显示全部,要求 " +
                    "userName显示姓名、avatar显示 ![DRAWING](头像地址)、gender性别、age显示年龄、workYears工作年限、" +
                    "displayTags技能标签、desiredSalary期望薪水、workExperiences工作经历、educationExperiences教育经历、newUserActiveTag用户最近状态、pageUrl用户简历地址";
        }
        switch (type) {
            case "chat":
                ChatMessage chatMessage = chatMessageMap.get(chatId);
                if (chatMessage != null) {
                    chatMessage.addUserMessage(msg);
                }else {
                    chatMessage = ChatMessage.newUserMessage(msg);
                    chatMessageMap.put(chatId, chatMessage);
                }
                ChatHandler.handler(ws, chatMessage);
                break;
            case "del":
                    chatMessageMap.remove(chatId);
                    break;
        }
    }

    @Override
    public void disConnect(Ws ws) {

    }

    public static void removeChatMessage(String chatId) {
        chatMessageMap.remove(chatId);
    }

}
